/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月16日
 */
package com.massyframework.beanskin.web.context;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.ServletContext;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.ModuleJarsLocator;
import com.massyframework.beanskin.ModuleRepository;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.assembly.AssemblyConfig;
import com.massyframework.beanskin.service.ServiceRepository;

/**
 * 装配件资源定位器
 * @author huangkh
 *
 */
class ModuleResourceLocator implements ResourceLocator {

	private static final String SEPARATOR = "/";

    private final Module<?> module;
    private final File resourceDir;

    /**
     * 构造方法
     * @param assembly {}
     */
    public ModuleResourceLocator(Module<?> module) {
        this.module = Objects.requireNonNull(
        		module, "\"module\" cannot be null.");

        this.resourceDir = module.getDataFile(".resources").toFile();
    }

    /**
     * 根据<code>path</code>定位资源的URL。
     *
     * @param path           {@link String},路径
     * @param servletContext {@link ServletContext},原始的Servlet上下文
     * @return {@link URL}
     * @throws MalformedURLException 如果<code>path</code>不符合规则，则抛出例外
     */
    @Override
    public URL getResource(String path, ServletContext servletContext) throws MalformedURLException {
        if (path == null) return null;
        if (path.startsWith("META-INF/")) {
    		ClassLoader classLoader = this.module.getModuleClassLoader();
    		return classLoader.getResource(path);
    	}

        URL result = null;
        try {
            result = servletContext.getResource(path);
        } catch (MalformedURLException e) {

        }

        if (result == null) {
            //在装配件 DataFile/resources目录下查找资源
            String effectivePath = this.getEffectivePath(path);
            File resFile = new File(resourceDir, effectivePath);
            if (resFile.exists()){
                result = resFile.toURI().toURL();
            }
        }
        
        return result;
    }

    /**
     * 返回Web应用程序中类似目录资源的下级资源列表,类似目录资源的路径以"/"结尾。<br>
     * 返回的路径都是相对于根目录，或者相对于Web应用程序的"/WEB-INF/lib"目录中的JAR文件的"/META-INF/resources"目录，并且具有前导"/"。
     *
     * <p>
     * <pre>
     * 例如，对于包含以下内容的Web应用程序：
     * /welcome.html
     * /catalog/index.html
     * /catalog/products.html
     * /catalog/offers/books.html
     * /catalog/offers/music.html
     * /customer/login.jsp
     * /WEB-INF/web.xml
     * /WEB-INF/classes/com.acme.OrderServlet.class
     * /WEB-INF/lib/catalog.jar!/META-INF/resources/catalog/moreOffers/books.html
     *
     * getResourcePaths("/")将返回{"/welcome.html","/catalog/","/customer/","/WEB-INF/"};
     * getResourcePaths("/catalog/")将返回{"/catalog/index.html","/catalog/products.html","/catalog/offers/","/catalog/moreOffers/"}。
     * </pre>
     *
     * @param path           {@link String},路径
     * @param servletContext {@link ServletContext},原始的Servlet上下文
     * @return {@link Set}
     */
    @Override
    public Set<String> getResourcePaths(String path, ServletContext servletContext) {
        if (path == null) return null;

        Set<String> result = servletContext.getResourcePaths(path);
        result = result == null ? new LinkedHashSet<>() : new LinkedHashSet<>(result);

        String effectivePath = this.getEffectivePath(path);

        File dir = new File(resourceDir, effectivePath);
        File[] files = dir.listFiles();
        if (files != null) {
	        for (File file : files) {
	            result.add(effectivePath.concat(SEPARATOR).concat(file.getName()));
	        }
        }
        return result;
    }


    /**
     * 有效的路径
     * @param path 路径
     * @return {@link String}
     */
    protected String getEffectivePath (String path){
        String result = null;
        if (path.startsWith(SEPARATOR)) {
            result = path.substring(1);
        } else {
            result = path;
        }

        return result;
    }
    
    /**
     * 取回嵌入的jars
     *
     * @return {@link List}
     */
    protected List<File> retrieveEmbedJarFiles () {
       
        if (module instanceof Assembly) {
        	List<File> result = new ArrayList<>();
        	Assembly assembly = (Assembly)module;
        	String text = assembly.getConfig().getParameter(AssemblyConfig.LIB_JARS);
            if (text != null) {
                String[] arr = text.split(",");
                for (String s : arr) {
                    File file = new File(s);
                    result.add(file);
                }
            }
            return result;
        }else {
        	ServiceRepository repo = ServiceRepository.retrieveFrom(this.module);
        	ModuleRepository moduleRepo = repo.getService(ModuleRepository.class);
        	Assembly kernel = moduleRepo.findModuleById(0, Assembly.class);
        	
        	ModuleJarsLocator locator = kernel.getAssemblyContext().getBean(ModuleJarsLocator.class);
        	List<URL> urls = locator.locate(this.module);
        	String protocal = "file";
        	
        	return urls.stream()
        			.filter( url -> url.getProtocol().equals(protocal))
        			.map( url -> new File(url.getFile()))
        			.collect(Collectors.toList());
        }
    }

}
